package com.cwx.mychat.websocket.message;

import com.cwx.mychat.entity.vo.MessageSendVo;
import com.cwx.mychat.utils.json.JsonUtil;
import com.cwx.mychat.utils.redis.RedisComponent;
import com.cwx.mychat.websocket.context.ChannelContextUtil;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Map;


/**
 * 作者： cwx
 * 时间： 2024/9/27 22:11
 * 版本： 1.0
 * 注释：
 */
@Component
@Slf4j
public class SendMessageHandler {

    private static final String MESSAGE_TOPIC = "message.topic";

    @Resource
    private RedissonClient redissonClient;


    @Autowired
    private ChannelContextUtil channelContextUtil;

    @PostConstruct
    public void listenMessage(){
        log.info("开始监听广播消息。。。");
        RTopic topic = redissonClient.getTopic(MESSAGE_TOPIC);
        topic.addListener(MessageSendVo.class, (MessageSendVo, sendDto) -> {
            if(sendDto.getSendUserId().startsWith("Urobot")){
                System.out.println("收到机器人消息:" + sendDto.getMessageContent());
            }else{
                log.info("收到广播消息: {}", JsonUtil.convertObj2Json(sendDto));
            }
            channelContextUtil.sendMsg(sendDto);
        });
    }

    //异步发送消息
    @Async("threadPoolTaskExecutor")
    public void sendMessage(MessageSendVo messageSendVo){
        try {
            // 暂停 1 秒
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("发送消息：{}", messageSendVo);
        RTopic topic = redissonClient.getTopic(MESSAGE_TOPIC);
        topic.publish(messageSendVo);
    }

    //同步发送消息
    public void sendSyncMessage(MessageSendVo messageSendVo){
        RTopic topic = redissonClient.getTopic(MESSAGE_TOPIC);
        topic.publish(messageSendVo);
    }


    //异步发送通知
    @Async("threadPoolTaskExecutor")
    public void sendNotice(Map<String, Object> notice){
        log.info("发送通知：{}", notice);
        RTopic topic = redissonClient.getTopic(MESSAGE_TOPIC);
        topic.publish(notice);
    }


}
